//
//  SHCompleteCustInfoContorller.m
//  JiFengDaRen
//
//  Created by SH_iOS on 2018/1/29.
//  Copyright © 2018年 SH_iOS. All rights reserved.
//


#import "SHCreditCardTfCell.h"
#import "SHTakePhotoCell.h"
#import "SHCompleteCustInfoContorller.h"

@interface SHCompleteCustInfoContorller ()<UITableViewDelegate,
                   UITableViewDataSource,SHTakePhotoCellDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,SHCreditCardTfCellDelegate>
@property(nonatomic,strong)UITableView *custInfoTableView;//主列表
@property(nonatomic,copy)NSArray *custInfoArray;//
@property(nonatomic,strong)SHCreditCardTfCell *bankCardNocell;
@property(nonatomic,copy)NSString *custCerCardFront;//身份证正面照
@property(nonatomic,copy)NSString *custCerCardBack;//身份证反面照
@property(nonatomic,copy)NSString *custBankCardFront;//银行卡正面照
@property(nonatomic,copy)NSString *custHandleCerAndBank;//手持身份证，银行卡


@end

@implementation SHCompleteCustInfoContorller
{
    NSInteger  buttonTag;
}

static NSString * const custInfoTakePhotoReuserId = @"takephoto";
static NSString * const custInfoPutBankCardReuserId = @"custInfoPutBankCardReuserId";

- (NSArray *)custInfoArray{
    return
    @[
        @{
            @"code":@"901",@"title":@"身份证正面照",@"imgUrl":self.custCerCardFront
          
        },
        @{
            @"code":@"902",@"title":@"身份证反面照",@"imgUrl":self.custCerCardBack
            
        },
        @{
            @"code":@"903",@"title":@"银行卡正面照",@"imgUrl":self.custBankCardFront
        
        },
        @{
            @"code":@"904",@"title":@"本人手持身份证及银行卡",@"imgUrl":self.custHandleCerAndBank
        
        },
             
    ];
}
#pragma mark - 主列表
- (UITableView *)custInfoTableView{
    
    if (!_custInfoTableView){
        
        _custInfoTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth,KScreenHeight - KNAVIGATIONBARHEIGHT) style:UITableViewStyleGrouped];
        
        _custInfoTableView.estimatedSectionHeaderHeight = 0;
        _custInfoTableView.estimatedSectionFooterHeight = 0;

        _custInfoTableView.backgroundColor = KBASEBGCOLOR;
        _custInfoTableView.estimatedRowHeight = 0;
        _custInfoTableView.separatorStyle = UITableViewCellSeparatorStyleNone;;
        
        _custInfoTableView.dataSource = self;
        
        _custInfoTableView.delegate = self;
        
        
        [_custInfoTableView registerClass:[SHTakePhotoCell class] forCellReuseIdentifier:custInfoTakePhotoReuserId];
        [_custInfoTableView registerClass:[SHCreditCardTfCell class] forCellReuseIdentifier:custInfoPutBankCardReuserId];

        
        
        
    }
    return _custInfoTableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    if (self.custInfoType == SHCompleteCustInfoCerCard){
        
        self.title  = @"身份验证";
        
    }else{
        
        self.title  = @"完善银行卡信息";

    }
    self.view.backgroundColor = KBASEBGCOLOR;
    [self.view addSubview:self.custInfoTableView];
    UIBarButtonItem *nexStepItem = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(nextStepAction:)];
    [nexStepItem setTitleTextAttributes:@{
                                          NSFontAttributeName : KSHSystemFont(14),
                                          NSForegroundColorAttributeName :KREDCOLOR,
                                          } forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem  = nexStepItem;
    // Do any additional setup after loading the view.
}

- (void)setBankCardCode:(NSString *)bankCardCode{
    
    _bankCardCode = bankCardCode;
    [self.custInfoTableView reloadData];
    
}

#pragma mark - tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (self.custInfoType == SHCompleteCustInfoCerCard) {
        
        return 2;
    }
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.custInfoType == SHCompleteCustInfoBankCard) {
        
        if (indexPath.section == 0) {
            
            return  __I6Height(45);
        }else{
            return  __I6Height(122);

        }
    }
    return __I6Height(122);

    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (self.custInfoType == SHCompleteCustInfoCerCard) {
        SHTakePhotoCell *takePhotoCell;
        takePhotoCell = [tableView dequeueReusableCellWithIdentifier:custInfoTakePhotoReuserId];
        takePhotoCell.delegate = self;
            switch (indexPath.section){
                case 0:
                    
                    takePhotoCell.imageUrl = self.custCerCardFront;
                    takePhotoCell.titleString = @"身份证正面照";
                    takePhotoCell.buttonTag =  901;

                    break;
                case 1:
                    
                    takePhotoCell.imageUrl = self.custCerCardBack;
                    takePhotoCell.titleString = @"身份证反面照";
                    takePhotoCell.buttonTag =  902;

                    
                    break;
                    
                    
                default:
                    break;
            }
            
            return takePhotoCell;

    }else{
        
        SHTakePhotoCell *takePhotoCell;
        
        if (indexPath.section == 0) {
            
            _bankCardNocell = [tableView dequeueReusableCellWithIdentifier:custInfoPutBankCardReuserId];
            _bankCardNocell.delegate = self;
            _bankCardNocell.labelText = @"银行卡号";
            [_bankCardNocell setContentTfContentHorizontal:UIControlContentHorizontalAlignmentLeft];
            _bankCardNocell.contentTf.enabled = NO;
            _bankCardNocell.contentTf.text = self.bankCardCode;

            return _bankCardNocell;
        }else{
            
            
            takePhotoCell = [tableView dequeueReusableCellWithIdentifier:custInfoTakePhotoReuserId];
            takePhotoCell.delegate = self;
            
            switch (indexPath.section) {
                case 1:
                    
                    takePhotoCell.imageUrl = self.custBankCardFront;
                    takePhotoCell.titleString = @"银行卡正面照";
                    takePhotoCell.buttonTag =  903;
                    
                    break;
                case 2:
                    
                    takePhotoCell.imageUrl = self.custHandleCerAndBank;
                    takePhotoCell.titleString = @"本人手持身份证及银行卡";
                    takePhotoCell.buttonTag =  904;
                    
                default:
                    break;
            }
            
        }
        
            return takePhotoCell;
        }
    
}



//设置组的头视图高度
- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        
        return __I6Height(50);
        
    }else{
        
        return __I6Height(15);
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headerView = [[UIView alloc]init];
  

    headerView.backgroundColor = KBASEBGCOLOR;
    if (section == 0){
        headerView.frame = CGRectMake(0, 0, KScreenWidth, __I6Height(50));
        SHLabel *headerLabel = [SHLabel labelWithText:@""font:13 textColor:[UIColor colorWithHexString:@"#666666"]
                                        textAlignment:NSTextAlignmentLeft];
        headerLabel.frame = CGRectMake(__I6Width(20), __I6Height(16), KScreenWidth, __I6Height(13));
        [headerView addSubview:headerLabel];
        if (self.custInfoType == SHCompleteCustInfoCerCard) {
            
            headerLabel.text = @"拍摄您的二代身份证原件，请确保图片清晰、四角完整";
        }else{
            
            headerLabel.text = @"拍摄您的银行卡照片，请确保图片清晰、四角完整";

        }
        
    }else{
        
        headerView.frame = CGRectMake(0, 0, KScreenWidth, __I6Height(15));

    }
    return headerView ;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.01;
}


#pragma mark - 拍照
- (void)takePhotoCell:(SHTakePhotoCell *)cell takePhotoButton:(UIButton *)button{
    
    //判断相机是否可用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        buttonTag = button.tag;
        //打开相机
        [self openImagePickerController:UIImagePickerControllerSourceTypeCamera];
        
    }else{
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"相机不可用" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alert show];
    }
    
}


#pragma mark - 打开相机
- (void)openImagePickerController:(UIImagePickerControllerSourceType)type{
    
    UIImagePickerController  *picker = [[UIImagePickerController alloc]init];
    //指定资源类型
    picker.sourceType = type;
    //允许编辑
//    picker.allowsEditing = YES;
    picker.delegate = self;
    //弹出
    [self presentViewController:picker animated:YES completion:nil];
    
    
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage * image  = info[UIImagePickerControllerOriginalImage];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage * thumbImage = [self imageCompressForWidth:image targetWidth:image.size.width * 0.1];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [SHQiniuManager qiniuUploadImage:thumbImage complete:^(NSString *qnImageUrl) {
        
        [MBProgressHUD  hideHUDForView:self.view animated:YES];
        switch (buttonTag) {
            case 901:
                self.custCerCardFront = qnImageUrl;
                break;
            case 902:
                self.custCerCardBack = qnImageUrl;
                break;

            case 903:
                self.custBankCardFront = qnImageUrl;
                break;
            case 904:
                self.custHandleCerAndBank = qnImageUrl;
                break;
            default:
                break;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{//在主线程刷新UI
            
            [self.custInfoTableView reloadData];
            
            
        });
        
    }];
    
    
}


-(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth
{
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = (targetWidth / width) * height;
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0,0,targetWidth,  targetHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (BOOL)creditCardTfCellTextField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    
    
    return YES;
}



#pragma mark - 提交
- (void)nextStepAction:(UIBarButtonItem *)item{
    
    if(self.custInfoType  ==  SHCompleteCustInfoCerCard){
        if (!self.custCerCardFront) {
            
            [self.view makeToast:@"请拍身份证正面照" duration:2.f position:@"center"];
            return;
        }
        if (!self.custCerCardBack) {
            
            [self.view makeToast:@"请拍身份证反面照" duration:2.f position:@"center"];
            return;
        }
        
        
        NSDictionary *params = @{@"idcard_front_pic":self.custCerCardFront,@"idcard_other_side_pic":self.custCerCardBack};
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
        [MyDataService requestAFURL:KREAL_NAME_AUTH_U  httpMethod:@"PUT" params:params data:nil complection:^(id result) {
            
        
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if ([result[@"success"] boolValue]) {
               
                [self.view makeToast:@"身份照片上传成功" duration:2.f position:@"center"];
                dispatch_time_t delayTimeOne = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5/*延迟执行时间*/ * NSEC_PER_SEC));
                
                
                dispatch_after(delayTimeOne, dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
         
            
        } failure:^(id erro) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];

            
        }];
    }else{
        
        if (!self.custBankCardFront) {
            
            [self.view makeToast:@"请拍银行卡正面照" duration:2.f position:@"center"];
            
        }
        if (!self.custHandleCerAndBank) {
            
            [self.view makeToast:@"请拍手持身份证,银行卡正面照" duration:2.f position:@"center"];
            return;
            
        }
        
        [SHCCRNet putCreditBankCardInfoBankCardCode:self.bankCardCode bankCardFrontPic:self.custBankCardFront personPhoto:self.custHandleCerAndBank success:^(id result) {
            
            dispatch_time_t delayTimeOne = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5/*延迟执行时间*/ * NSEC_PER_SEC));
            
            dispatch_after(delayTimeOne, dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];

            });
                        
                           
        } complection:^(id result) {
            
        } failure:^(id erro) {
            
        }];
        
    }
    
    SHLog(@"拍完照下一步");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
